package gw.com.android.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Created by spence on 17-8-31.
 */

public class ZipUtils {

  /**
   * 压缩制定目录的文件
   * @param srcFilePath 即将压缩文件的目录路径
   * @param zipFilePath 生成zip文件的路径(含文件名如:sccard/xxx.zip)
   */
  public static boolean zipFolder(String srcFilePath, String zipFilePath){

    // 创建Zip包

    try {

      ZipOutputStream outZip = new ZipOutputStream(new FileOutputStream(

          zipFilePath));

      // 打开要输出的文件

      File file = new File(srcFilePath);

      // 压缩

      zipFiles(file.getParent() + File.separator, file.getName(), outZip);

      // 完成,关闭

      outZip.finish();

      outZip.close();
    }catch (Exception e){
      return false;
    }
    return true;

  }

  private static void zipFiles(String folderPath, String filePath, ZipOutputStream zipOut)

      throws Exception {

    if (zipOut == null) {

      return;

    }

    File file = new File(folderPath + filePath);


    // 判断是不是文件

    if (file.isFile()) {

      ZipEntry zipEntry = new ZipEntry(filePath);

      FileInputStream inputStream = new FileInputStream(file);

      zipOut.putNextEntry(zipEntry);


      int len;

      byte[] buffer = new byte[100000];


      while ((len = inputStream.read(buffer)) != -1) {

        zipOut.write(buffer, 0, len);

      }

      inputStream.close();

      zipOut.closeEntry();

    } else {

      // 文件夹的方式,获取文件夹下的子文件

      String fileList[] = file.list();

      // 如果没有子文件, 则添加进去即可

      if (fileList.length <= 0) {

        ZipEntry zipEntry = new ZipEntry(filePath + File.separator);

        zipOut.putNextEntry(zipEntry);

        zipOut.closeEntry();

      }

      // 如果有子文件, 遍历子文件

      for (int i = 0; i < fileList.length; i++) {

        zipFiles(folderPath, filePath + File.separator + fileList[i], zipOut);

      }

    }

  }

}
